import 'package:flutter/material.dart';
import 'package:get/get.dart';

import '../services/storage/local_storage_service.dart';

/// 语言控制器
/// 负责管理应用的语言设置
class LanguageController extends GetxController {
  // 单例访问器
  static LanguageController get to => Get.find();
  
  // 注入服务
  final LocalStorageService _storageService = Get.find<LocalStorageService>();
  
  // 当前语言区域
  final Rx<Locale> _locale = const Locale('zh', 'CN').obs;
  Locale get locale => _locale.value;
  
  // 语言存储键
  static const String languageKey = 'app_language';
  
  // 支持的语言
  final List<Map<String, dynamic>> supportedLanguages = [
    {'name': '简体中文', 'locale': const Locale('zh', 'CN')},
    {'name': '繁體中文', 'locale': const Locale('zh', 'TW')},
    {'name': 'English', 'locale': const Locale('en', 'US')},
  ];
  
  @override
  void onInit() {
    super.onInit();
    
    // 初始化语言设置
    _loadLanguage();
  }
  
  /// 加载保存的语言设置
  void _loadLanguage() {
    final String? savedLanguage = _storageService.read(languageKey);
    
    if (savedLanguage != null) {
      final parts = savedLanguage.split('_');
      if (parts.length == 2) {
        final Locale newLocale = Locale(parts[0], parts[1]);
        
        // 检查是否在支持的语言中
        if (_isLocaleSupported(newLocale)) {
          _locale.value = newLocale;
          _updateLocale(newLocale);
        }
      }
    } else {
      // 使用设备语言或默认语言
      final deviceLocale = Get.deviceLocale;
      if (deviceLocale != null && _isLocaleSupported(deviceLocale)) {
        _locale.value = deviceLocale;
      } else {
        _locale.value = const Locale('zh', 'CN'); // 默认简体中文
      }
      
      _updateLocale(_locale.value);
    }
  }
  
  /// 更改应用语言
  void changeLanguage(Locale locale) {
    if (_isLocaleSupported(locale)) {
      _locale.value = locale;
      
      // 保存设置
      _storageService.write(
        languageKey, 
        '${locale.languageCode}_${locale.countryCode}'
      );
      
      // 更新GetX语言
      _updateLocale(locale);
    }
  }
  
  /// 更新GetX语言
  void _updateLocale(Locale locale) {
    Get.updateLocale(locale);
  }
  
  /// 获取当前语言名称
  String get currentLanguageName {
    final current = supportedLanguages.firstWhere(
      (lang) => lang['locale'] == _locale.value,
      orElse: () => supportedLanguages.first,
    );
    return current['name'] as String;
  }
  
  /// 检查区域是否被支持
  bool _isLocaleSupported(Locale locale) {
    return supportedLanguages.any(
      (lang) => (lang['locale'] as Locale).languageCode == locale.languageCode &&
        (lang['locale'] as Locale).countryCode == locale.countryCode
    );
  }
} 